const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');

const request = require('../utils/request')
const User = require('../models/User');
const { SECRET_KEY, Expiration } = require('../config/authConfig');

class UserService {
  // 获取所有用户
  async getUsers() {
    try {
      return await User.findAll({
        attributes: ['id', 'name', 'email', 'createdAt', 'updatedAt']
      });
    } catch (error) {
      throw new Error('获取用户列表失败');
    }
  }

  // 获取单个用户
  async getUser(id) {
    try {
      return await User.findOne({
        where: { id },
        attributes: ['id', 'name', 'email', 'role', 'createdAt', 'updatedAt']
      });
    } catch (error) {
      throw new Error('获取用户失败');
    }
  }

  // 获取单个用户
  async getUserByOpenid(openid) {
    try {
      return await User.findOne({
        where: { openid },
        attributes: ['id', 'name', 'email', 'role', 'createdAt', 'updatedAt']
      });
    } catch (error) {
      throw new Error('获取用户失败');
    }
  }

  // 创建用户
  async createUser({ name, password, openid }) {
    try {
      // 检查用户是否已存在
      const whereOpt = {}
      name && Object.assign(whereOpt, {name})
      openid && Object.assign(whereOpt, {openid})

      const existingUser = await User.findOne({ where: whereOpt });
      if (existingUser) {
        return false;
      }

      // 生成密码哈希
      const hashedPassword = await bcrypt.hash(password, 10);
      const user = { name, password: hashedPassword }
      
      openid && Object.assign(user, {openid})

      // 创建新用户
      const { id, name: username, updatedAt, createdAt } = await User.create(user);

      return { id, name: username, updatedAt, createdAt };
    } catch (error) {
      throw new Error('创建用户失败');
    }
  }

  // 更新用户
  async updateUser({ id, name, email, password }) {
    try {
      const res = await User.update({ name, email, password }, { where: { id } });
      return res[0] > 0 ? true : false;
    } catch (error) {
      throw new Error('更新用户失败');
    }
  }

  // 删除用户
  async deleteUser(id) {
    try {
      const res = await User.destroy({ where: { id } });
      return res ? true : false;
    } catch (error) {
      throw new Error('删除用户失败');
    }
  }

  // 批量删除用户
  async deleteUsers(ids) {
    try {
      const res = await User.destroy({ where: { id: ids } });
      return res ? true : false;
    } catch (error) {
      throw new Error('批量删除用户失败');
    }
  }

  // 用户登录
  async loginUser({ name, password }) {
    try {
      // 查找用户
      const user = await User.findOne({ where: { name } });

      if (!user) {
        // 用户不存在
        throw new Error('用户名或密码错误');
      }

      // 验证密码
      const isPasswordValid = await bcrypt.compare(password, user.password);

      if (!isPasswordValid) {
        // 密码不匹配
        throw new Error('用户名或密码错误');
      }

      // 生成 JWT
      const token = jwt.sign({ id: user.id, name: user.name, role: user.role }, SECRET_KEY, { expiresIn: Expiration });
      return token
    } catch (error) {
      throw new Error('登录失败');
    }
  }


  // 获取openid
  async getUserOpenID(code) {
    try {
      const startTime = Date.now()
      const res = await request.get(`https://api.weixin.qq.com/sns/jscode2session`, {
        appid: 'wx57a32f7f0189276f',
        secret: '3249586f74d09218b833bd9a56d7a1f0',
        js_code: code,
        grant_type: 'authorization_code'
      }); // 发送请求到服务器获取用户 OpenID
      const endTime = Date.now();
      const responseTime = endTime - startTime;
      console.log(responseTime,'openid响应时间');
      return res;
    } catch (error) {
      // console.log(error);
      throw new Error('获取用户 OpenID 失败。');
    }
  }
}

module.exports = new UserService();